package cn.akwangl.demo;

/**
 * 利用三个线程按字母顺序打印A、B、C.
 * <p>
 * 验证synchronized争抢锁是否有队列?
 * 有,但是唤醒这是个非公平的.所以为了保证唤醒顺序,在线程启动时刻意sleep 550毫秒,另外创建了三把锁是为了保证,调用{@link Object#wait()}方法,
 * 休眠的对象只有一个.
 *
 * @author 阿坤同学
 * @date 2022-11-15 11:19
 */
public class OrderPrint {

    static Object printALock = new Object();
    static Object printBLock = new Object();
    static Object printCLock = new Object();

    public static void main(String[] args) {
        Task taskA = new Task("A", printALock, printBLock);
        Task taskB = new Task("B", printBLock, printCLock);
        Task taskC = new Task("C", printCLock, printALock);
        Thread t1 = new Thread(taskA);
        Thread t2 = new Thread(taskB);
        Thread t3 = new Thread(taskC);


        try {
            t1.start();
            Thread.sleep(550);
            t2.start();
            Thread.sleep(550);
            t3.start();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    static class Task implements Runnable {

        private final String printContent;
        private Object printLock;
        private Object nexPrintLock;

        public Task(String printContent, Object printLock, Object nexPrintLock) {
            this.printContent = printContent;
            this.printLock = printLock;
            this.nexPrintLock = nexPrintLock;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (printLock) {
                    String outStr = String.format("线程:%s,当前打印内容:%s", Thread.currentThread().getName(), printContent);
                    System.err.println(outStr);

                    try {
                        Thread.sleep(500L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                    synchronized (nexPrintLock) {
                        nexPrintLock.notify();
                    }
                    if ("C".equals(printContent)) {
                        System.err.println("-----------------------------------------------");
                    }

                    try {
                        printLock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}